package com.android.nurse;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class RankingActivity extends CommonActivity {

	private RankAdapter rAdapter;
	private LocalRankingInfo l;
	private int currentPost = -1;
	private String color;
	private ListView lView;
	private LocalRankingInfo infoItem;
	private Button back;
	private ArrayList<LocalRankingInfo> lArrayList;
	private LocalRanking lR;
	private int width;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		super.onCreate(savedInstanceState);
		Display display = ((WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		width = display.getWidth();
		Log.d("chieu rong man hinh", ""+width);
		if(width > 500){
			setContentView(R.layout.ranking_big);
		} else {
		setContentView(R.layout.ranking);
		}
		lView = (ListView) findViewById(R.id.listRank);
		lView.setCacheColorHint(00000);
		this.getData();
		
		// tao ra doi tuong local rank 
		lR = new LocalRanking(l, getApplicationContext());
		lArrayList = lR.getListLocalRank();
		if(l != null && !LocalRanking.isAddedNew() ){
			lArrayList.add(l);
			LocalRanking.addedNew = true;
		}
		if (lArrayList != null) {
			if (l != null) {
				for (int i = 0; i < lArrayList.size(); i++) {
					LocalRankingInfo ls = lArrayList.get(i);
					if (ls.getNurseType() == l.getNurseType()
							&& ls.getTiredScore() == l.getTiredScore()
							&& ls.getUsername().equals(l.getUsername())) {
						currentPost = i;
						break;
					}
				}
			}
			Log.d("cur", "Cur:" + currentPost);
			rAdapter = new RankAdapter(getApplicationContext(),
					R.layout.rankrow, lArrayList);
			lView.setAdapter(rAdapter);
			if (currentPost > 0) {
				lView.setSelectionFromTop(currentPost, 100);
			}
		}
		back = (Button) findViewById(R.id.backButton);
	}

	private void getData() {
		SharedPreferences settings = getSharedPreferences(
				QuestionsScreen.PREFS_NAME, 0);
		if (settings != null && settings.getInt("VIEWED", 0) == 1) {
			Log.d("vao", "Van vao day" + settings.getInt("VIEWED", 0));
			l = new LocalRankingInfo();
			l.setUsername(settings
					.getString(LogInScreen.userName, "not exits!"));
			l.setAge(settings.getInt(LogInScreen.ageNurse, -1));
			l.setNurseType(settings.getInt("ID_NURSE", -1));
			l.setTiredScore(settings.getInt("TIRED_POINT", -1));
			if (l.getAge() == -1) {
				l = null;
			} else {
				SharedPreferences.Editor edit = settings.edit();
				edit.remove("VIEWED");
				edit.commit();
				Log.d("vao", "da vao setting" + settings.getInt("VIEWED", 0));
			}
		} else {
			l = null;
		}
	}

	private void sendData() {
		SharedPreferences settings = getSharedPreferences(
				QuestionsScreen.PREFS_NAME, 0);
		SharedPreferences.Editor edit = settings.edit();
		edit.putString(LogInScreen.userName, infoItem.getUsername());
		edit.putInt(QuestionsScreen.ID_NURSE, infoItem.getNurseType());
		edit.putInt(QuestionsScreen.TIRED_POINT, infoItem.getTiredScore());
		edit.commit();
	}

	private class RankAdapter extends ArrayAdapter<LocalRankingInfo> {

		private ArrayList<LocalRankingInfo> items;

		public RankAdapter(Context context, int textViewResourceId,
				ArrayList<LocalRankingInfo> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View v = convertView;
			
			// if (v == null) {
			LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			if(width > 500){
				v = vi.inflate(R.layout.rankrow_big, null);
			} else {
			v = vi.inflate(R.layout.rankrow, null);
			 }
			ImageView posImage = (ImageView) v.findViewById(R.id.positionImage);
			TextView nurseType = (TextView) v.findViewById(R.id.nurseType);
			TextView nurseName = (TextView) v.findViewById(R.id.nurseName);
			TextView globalTextView = (TextView) v.findViewById(R.id.global);

			ImageView nurseFace = (ImageView) v.findViewById(R.id.nurseFace);
			TextView painLabel = (TextView) v.findViewById(R.id.pain);
			TextView tiredScore = (TextView) v.findViewById(R.id.tiredScore);
			if (position == currentPost) {
				v.setBackgroundColor(getResources().getColor(R.color.bg_color));
				Log.d("num", "pos:" + position + " cur:" + currentPost);
				color = "#FF0099";
			} else {
				color = "#FF0099";
			}

			LocalRankingInfo localRankingInfo = items.get(position);
			if (localRankingInfo != null) {
				if (position < 10) {
					posImage.setImageResource(getResources().getIdentifier(
							"ico_ranking_" + (position + 1), "drawable",
							getPackageName()));
				} else {
					posImage.setImageResource(R.drawable.ico_ranking_kengai);
				}
				NurseType nType = getNurseType(localRankingInfo.getNurseType());
				nurseType.setText(Html.fromHtml("<font color=\"#FF0099\">"
						+ nType.getName() + "</font>"
						+ "<font color=\"#990000\">ナース</font>"));
				nurseName.setText(Html.fromHtml("<font color=\"#FF0099\">"
						+ localRankingInfo.getUsername() + "</font>"
						+ "<font color=\"#990000\">さん</font>"));
				if (!localRankingInfo.getGlobalPosition().equals("null") && getShowRanking()) {
					globalTextView.setText(Html
							.fromHtml("<font color=\"#990000\"> 全国順位 "
									+ localRankingInfo.getGlobalPosition()
									+ "</font>"));
				} else {
					((ViewManager) globalTextView.getParent())
							.removeView(globalTextView);
				}
				nurseFace.setImageResource(getResources().getIdentifier(
						nType.getImageRanking(), "drawable", getPackageName()));
				painLabel.setText(Html.fromHtml("<font color=\"" + color
						+ "\">" + "お疲れ度" + "</font>"));
				tiredScore.setText(Html.fromHtml("<font color=\"" + color
						+ "\">" + localRankingInfo.getTiredScore() + "%"
						+ "</font>"));
			}
			return v;
		}
	}

	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub
		super.onAttachedToWindow();
		back.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction() & MotionEvent.ACTION_MASK) {

				case MotionEvent.ACTION_DOWN:
					back.setBackgroundResource(R.drawable.btn_back_2);
					break;
				case MotionEvent.ACTION_UP:
					back.setBackgroundResource(R.drawable.btn_back);
					Intent i = new Intent(getApplicationContext(),
							TopScreen.class);
					backScreen(i);
					break;
				}
				return true;
			}
		});
		lView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				infoItem = (LocalRankingInfo) lView
						.getItemAtPosition(position);
				sendData();
				Intent i = new Intent(getApplicationContext(),
						ExplainedScreen.class);
				//i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
				customeActivity(i);
			}
		});
	}
	
	@Override
	public void onBackPressed() {
	   return;
	}
	
}
